﻿using ACMESharp.Authorizations;
using PKISharp.WACS.DomainObjects;
using PKISharp.WACS.Plugins.Base.Factories;
using PKISharp.WACS.Services;
using PKISharp.WACS.Services.Serialization;
using System.Linq;
using System.Threading.Tasks;

namespace PKISharp.WACS.Plugins.ValidationPlugins.Dns
{
    internal sealed class AliDnsOptionsFactory : ValidationPluginOptionsFactory<AliDns, AliDnsOptions>
    {
        private readonly ArgumentsInputService _arguments;
        public AliDnsOptionsFactory(ArgumentsInputService arguments) : base(Dns01ChallengeValidationDetails.Dns01ChallengeType) => _arguments = arguments;

        private ArgumentResult<ProtectedString?> ApiSecret => _arguments.
            GetProtectedString<AliDnsArguments>(a => a.AliDnsSecret).
            Required();

        private ArgumentResult<string?> AccessKey => _arguments.
            GetString<AliDnsArguments>(a => a.AliDnsAccessKey).
            Required();

        public override async Task<AliDnsOptions?> Aquire(Target target, IInputService input, RunLevel runLevel)
        {
            return new AliDnsOptions
            {
                AccessKeyID = await AccessKey.Interactive(input, "AccessKey ID").GetValue(),
                AccessKeySecret = await ApiSecret.Interactive(input, "AccessKey Secret").GetValue()
            };
        }

        public override async Task<AliDnsOptions?> Default(Target target)
        {
            return new AliDnsOptions
            {
                AccessKeySecret = await ApiSecret.GetValue(),
                AccessKeyID = await AccessKey.GetValue()
            };
        }

        public override bool CanValidate(Target target) => target.Parts.SelectMany(x => x.Identifiers).All(x => x.Type == IdentifierType.DnsName);
    }
}
